<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="modalTitle" @ok="onButtonOkClick">
    <BasicTree
      v-if="treeData.length"
      title="部门列表"
      ref="treeRef"
      :clickRowToExpand="false"
      :checkable="true"
      :checkStrictly="true"
      :treeData="treeData"
      :checkedKeys="checkedKeys"
      :showLine="{ showLeafIcon: false }"
      :defaultExpandAll="true"
    />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, inject, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { OperationTypeEnum } from '/@/enums/appEnum';

  import { BasicTree, TreeItem, TreeActionType } from '/@/components/Tree';

  import { getDepts, setDepts } from '/@/api/cms/category';

  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'SetRoleDepts',
    components: {
      BasicTree,
      BasicModal,
    },
    setup(_, { emit }) {
      //弹出窗口界面是关联部门设置
      const op = ref(OperationTypeEnum.UN_KNOWN);
      const moduleName = inject<string>('moduleName');
      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');

      const treeRef = ref<Nullable<TreeActionType>>(null);
      function getTree() {
        const tree = unref(treeRef);
        if (!tree) {
          throw new Error('tree is null!');
        }
        return tree;
      }

      //栏目id集合
      const cids = ref<number[] | string[]>([]);

      const treeData = ref<TreeItem[]>([]);

      //已经关联的key
      const checkedKeys = ref<number[] | string[]>([]);

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        //每次打开不同栏目窗口都会添加一次栏目id,接收前如果有则清空
        if (cids.value.length > 0) {
          cids.value = [];
        }
        //接收父组件传递的数据
        console.log(data);

        if (data?.op) {
          op.value = data.op;
        }

        if (data?.dataId) {
          cids.value.push(data.dataId);
        }
        //批量设置部门的栏目id集合
        if (data?.cids) {
          cids.value = data.cids;
        }

        if (moduleName) {
          modalTitle.value = unref(moduleName);
        }

        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        setModalProps({ confirmLoading: false });

        getDeptList();
      });

      //获取部门信息
      async function getDeptList() {
        //每次打开窗口都会重复加载数据，在加载数据前如果有数据先清空
        if (treeData.value.length > 0) {
          treeData.value = [];
        }
        if (checkedKeys.value.length > 0) {
          checkedKeys.value = [];
        }
        //调用后端接口获取数据
        getDepts(cids.value)
          .then((res) => {
            console.log('res', res);
            //处理返回数据
            let level1Node = [];
            let level2Node = [];
            let level3Node = [];

            res.forEach((deptNode) => {
              if (deptNode.dept.level == 0) {
                level1Node.push(deptNode);
              }
              if (deptNode.dept.level == 1) {
                level2Node.push(deptNode);
              }
              if (deptNode.dept.level == 2) {
                level3Node.push(deptNode);
              }
              //获取设置部门之前已经关联的部门id，用于回显勾选
              if (deptNode.checked === true) {
                checkedKeys.value.push(deptNode.dept.id);
              }
            });
            // console.log('已经关联的部门', checkedKeys.value);

            //第一层
            level1Node.forEach((level1) => {
              let nodeData = {
                title: level1.dept.name,
                key: level1.dept.id,
                children: [],
              };
              //第二层
              level2Node.forEach((level2) => {
                let childNodeData1 = {
                  title: level2.dept.name,
                  key: level2.dept.id,
                  children: [],
                };
                if (level2.dept.parentid == level1.dept.id) {
                  nodeData.children.push(childNodeData1);
                }

                //第三层
                level3Node.forEach((level3) => {
                  let childNodeData2 = {
                    title: level3.dept.name,
                    key: level3.dept.id,
                    children: [],
                  };
                  if (level3.dept.parentid == level2.dept.id) {
                    childNodeData1.children.push(childNodeData2);
                  }
                  //第四层
                });
              });

              treeData.value.push(nodeData);
              // console.log('部门树数据', treeData.value);
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，调用接口保存关联信息
       */
      async function onButtonOkClick() {
        //获取勾选的部门节点
        const dids = getTree().getCheckedKeys();
        console.log('获取勾选的key', dids);
        if (dids != null) {
          if (dids.checked != undefined) {
            // console.log('获取情况一勾选的key1', dids.checked);
            try {
              setModalProps({ confirmLoading: true });
              //调用接口进行保存
              setDepts({ cids: cids.value, dids: dids.checked })
                .then((res) => {
                  if (!res || Object.keys(res).length == 0) {
                    createMessage.success('设置成功', 2);
                  }
                  closeModal();
                  emit('success');
                })
                .catch((ex) => {
                  console.log('catch ', ex);
                  createMessage.error(ex.msg);
                });
            } finally {
              setModalProps({ confirmLoading: false });
            }
          } else {
            // console.log('获取情况二勾选的key2', dids);
            try {
              setModalProps({ confirmLoading: true });
              //调用接口进行保存
              setDepts({ cids: cids.value, dids: dids })
                .then((res) => {
                  if (!res || Object.keys(res).length == 0) {
                    createMessage.success('设置成功', 2);
                  }
                  closeModal();
                  emit('success');
                })
                .catch((ex) => {
                  console.log('catch ', ex);
                  createMessage.error(ex.msg);
                });
            } finally {
              setModalProps({ confirmLoading: false });
            }
          }
        }
        // 清空选中的行;
        checkedKeys.value = [];
      }

      return {
        op,
        moduleName,
        modalTitle,
        registerModal,
        getDeptList,
        onButtonOkClick,
        treeData,
        checkedKeys,
        treeRef,
      };
    },
  });
</script>
